//#######################################################################################################
//######################################### Plugin-250: SendHTTP ########################################
//#######################################################################################################

/*********************************************************************************************\
 * This protocol provides direct peer-to-peer HTTP communication between Nodo unit's
 * 
 * Author             : Martinus van den Broek
 * Support            : None!
 * Date               : Jul 2014
 * Version            : 0.1
 * Compatibility      : R744
 * Syntax             : "sendHTTP <last octet of local ip address>,<port number>
 \*********************************************************************************************/

boolean P250SendCustomHTTPRequest(char* Request, byte ip, unsigned long port);

#define PLUGIN_ID 250
#define PLUGIN_NAME "SendHTTP"

boolean Plugin_250(byte function, struct NodoEventStruct *event, char *string)
{
  static boolean watchdog = false;
  boolean success=false;

  switch(function)
  {
#ifdef PLUGIN_250_CORE

  #if NODO_MEGA
  case PLUGIN_COMMAND:
    {
      byte x;
      char *HttpRequest=(char*)malloc(INPUT_LINE_SIZE+1);
      char *TempString=(char*)malloc(INPUT_LINE_SIZE+1);

      strcpy(HttpRequest,"?event=");
      Event2str(&LastReceived,TempString);
      strcat(HttpRequest,TempString);
      free(TempString);
      x=P250SendCustomHTTPRequest(HttpRequest,event->Par1,event->Par2);
      free(HttpRequest);

      success=true;
      break;
     }
  #endif

#endif // PLUGIN_250_CORE

    #if NODO_MEGA
    case PLUGIN_MMI_IN:
      {
      char *TempStr=(char*)malloc(26);
      string[25]=0;
      if(GetArgv(string,TempStr,1))
        {
        if(strcasecmp(TempStr,PLUGIN_NAME)==0)
          {
          if(GetArgv(string,TempStr,2)) 
            {
              event->Type = NODO_TYPE_PLUGIN_COMMAND;
              event->Command = 250;
              success=true;
            }
          }
        }
      free(TempStr);
      break;
      }

    case PLUGIN_MMI_OUT:
      {
      strcpy(string,PLUGIN_NAME);            // Commando / event 
      strcat(string," ");                
      strcat(string,int2str(event->Par1));
      strcat(string,",");                
      strcat(string,int2str(event->Par2));
      break;
      }
    #endif

  }

  return success;
}

#define IP_BUFFER_SIZE            256

boolean P250SendCustomHTTPRequest(char* Request, byte ip, unsigned long port)
  {
  byte targetIP[4];
  int InByteCounter,x,y;
  byte InByte;
  unsigned long TimeoutTimer;
  const int TimeOut=5000;
  EthernetClient HTTPClient; // Client class voor HTTP sessie.
  byte State=0;
  char *IPBuffer=(char*)malloc(IP_BUFFER_SIZE+1);

  targetIP[0] = EthernetNodo.localIP()[0];
  targetIP[1] = EthernetNodo.localIP()[1];
  targetIP[2] = EthernetNodo.localIP()[2];
  targetIP[3] = ip;

  strcpy(IPBuffer,"GET ");

  // Alle spaties omzetten naar %20 en toevoegen aan de te verzenden regel.
  y=strlen(IPBuffer);
  for(x=0;x<strlen(Request);x++)
    {            
    if(Request[x]==32)
      {
      IPBuffer[y++]='%';
      IPBuffer[y++]='2';
      IPBuffer[y++]='0';
      }
    else
      {
      IPBuffer[y++]=Request[x];
      }
    }
  IPBuffer[y]=0;

  if(HTTPClient.connect(targetIP,port))
    {
      HTTPClient.println(IPBuffer);
      HTTPClient.println(F("Connection: Close"));
      HTTPClient.println();// Afsluiten met een lege regel is verplicht in http protocol/

      TimeoutTimer=millis()+TimeOut; // Als er te lange tijd geen datatransport is, dan wordt aangenomen dat de verbinding (om wat voor reden dan ook) is afgebroken.

      while(TimeoutTimer>millis() && HTTPClient.connected())
        {
        if(HTTPClient.available())
          {
            InByte=HTTPClient.read();
          
            if(isprint(InByte) && InByteCounter<IP_BUFFER_SIZE)
              IPBuffer[InByteCounter++]=InByte;

            else if(InByte==0x0A)
              {
                IPBuffer[InByteCounter]=0;
                // De regel is binnen 
                InByteCounter=0;          
              }
          }
        }

//      delay(100); ?????
      HTTPClient.flush();// Verwijder eventuele rommel in de buffer.
      HTTPClient.stop();
    }
  free(IPBuffer);
  return State;
  }

